package com.atguigu.tingshu.search.service.impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.FieldValue;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.aggregations.Aggregate;
import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.core.search.Suggestion;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.album.client.CategoryFeignClient;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.PinYinUtils;
import com.atguigu.tingshu.model.album.*;
import com.atguigu.tingshu.model.search.AlbumInfoIndex;
import com.atguigu.tingshu.model.search.AttributeValueIndex;
import com.atguigu.tingshu.model.search.SuggestIndex;
import com.atguigu.tingshu.query.search.AlbumIndexQuery;
import com.atguigu.tingshu.search.repository.AlbumIndexRepository;
import com.atguigu.tingshu.search.repository.SuggestIndexRepository;
import com.atguigu.tingshu.search.service.SearchService;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.vo.search.AlbumInfoIndexVo;
import com.atguigu.tingshu.vo.search.AlbumSearchResponseVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.suggest.Completion;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


@Slf4j
@Service
@SuppressWarnings({"all"})
public class SearchServiceImpl implements SearchService {

    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;

    @Autowired
    private CategoryFeignClient categoryFeignClient;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    @Autowired
    private AlbumIndexRepository albumIndexRepository;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private ElasticsearchClient elasticsearchClient;

    @Autowired
    private SuggestIndexRepository suggestIndexRepository;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<AlbumInfoIndex> findRankingList(Long category1Id, String ranking) {
       List<AlbumInfoIndex> list = (List<AlbumInfoIndex>) redisTemplate.opsForHash().get(RedisConstant.RANKING_KEY_PREFIX+category1Id,ranking);
       return list;
    }

    @Override
/**
 * 根据查询条件搜索专辑信息
 *
 * @param albumIndexQuery 专辑索引查询对象，包含查询所需的各种参数
 * @return 返回一个包含搜索结果的专辑搜索响应对象
 */
    public AlbumSearchResponseVo search(AlbumIndexQuery albumIndexQuery) {
        // 构建搜索请求
        SearchRequest searchRequest = this.queryBuildDsl(albumIndexQuery);
        SearchResponse<AlbumInfoIndex> searchResponse = null;
        try {
            // 执行搜索请求
            searchResponse = elasticsearchClient.search(searchRequest, AlbumInfoIndex.class);
        } catch (IOException e) {
            // 搜索失败时抛出运行时异常
            throw new RuntimeException(e);
        }
        // 解析搜索结果
        AlbumSearchResponseVo searchResponseVo = this.parseResultData(searchResponse);
        // 设置搜索结果的总数量
        searchResponseVo.setTotal(searchResponse.hits().total().value());
        // 设置每页的大小
        searchResponseVo.setPageSize(albumIndexQuery.getPageSize());
        // 设置当前页码
        searchResponseVo.setPageNo(albumIndexQuery.getPageNo());
        // 计算并设置总页数
        searchResponseVo.setTotalPages(searchResponseVo.getTotal() % albumIndexQuery.getPageSize() == 0 ?
                searchResponseVo.getTotal() / albumIndexQuery.getPageSize() :
                searchResponseVo.getTotal() / albumIndexQuery.getPageSize() + 1);
        // 另一种计算总页数的方法
        Long totalPages = (searchResponseVo.getTotal() + searchResponseVo.getPageSize() - 1) / searchResponseVo.getPageSize();
        searchResponseVo.setTotalPages(totalPages);
        // 返回搜索结果对象
        return searchResponseVo;
    }

    /**
     * 解析搜索响应数据，将其转换为专辑搜索响应对象
     *
     * @param searchResponse 搜索响应对象，包含从Elasticsearch中获取的数据
     * @return 返回一个填充了搜索结果数据的专辑搜索响应对象
     */
    private AlbumSearchResponseVo parseResultData(SearchResponse<AlbumInfoIndex> searchResponse) {
        AlbumSearchResponseVo albumSearchResponseVo = new AlbumSearchResponseVo();
        // 将搜索结果中的每个命中项转换为专辑信息视图对象
        List<AlbumInfoIndexVo> albumInfoIndexVoList = searchResponse.hits().hits().stream().map(hit ->
                {
                    AlbumInfoIndexVo albumInfoIndexVo = new AlbumInfoIndexVo();
                    AlbumInfoIndex albumInfoIndex = hit.source();
                    BeanUtils.copyProperties(albumInfoIndex, albumInfoIndexVo);
                    // 如果存在高亮标题，则设置高亮标题
                    if (null != hit.highlight().get("albumTitle")) {
                        String albumTitle = hit.highlight().get("albumTitle").get(0);
                        albumInfoIndexVo.setAlbumTitle(albumTitle);
                    }
                    return albumInfoIndexVo;
                }
        ).collect(Collectors.toList());

        // 将转换后的专辑信息视图对象列表设置到响应对象中
        albumSearchResponseVo.setList(albumInfoIndexVoList);

        return albumSearchResponseVo;
    }

    /**
     * 根据查询条件构建Elasticsearch搜索请求
     *
     * @param albumIndexQuery 专辑索引查询对象，包含查询所需的各种参数
     * @return 返回一个构建好的搜索请求对象
     */
    public SearchRequest queryBuildDsl(AlbumIndexQuery albumIndexQuery) {
        // 创建搜索请求构建器
        SearchRequest.Builder searchRequsetBuilder = new SearchRequest.Builder();
        // 设置索引名称
        searchRequsetBuilder.index("albuminfo");
        // 创建布尔查询构建器
        BoolQuery.Builder boolQuerybuilder = new BoolQuery.Builder();
        // 如果关键词不为空，则添加匹配查询条件
        if (!StringUtils.isEmpty(albumIndexQuery.getKeyword())) {
            boolQuerybuilder.should(s -> s.match(m -> m.field("albumTitle").query(albumIndexQuery.getKeyword()))).
                    should(s -> s.match(m -> m.field("albumIntro").query(albumIndexQuery.getKeyword()))).
                    should(s -> s.match(m -> m.field("announcerName").query(albumIndexQuery.getKeyword())));
            // 设置高亮字段
            searchRequsetBuilder.highlight(h -> h.fields("albumTitles", f -> f.preTags("<span style=color:red").postTags("</span>")));
        }
        // 如果一级分类ID不为空，则添加过滤条件
        if (!StringUtils.isEmpty(albumIndexQuery.getCategory1Id())) {
            boolQuerybuilder.filter(f -> f.term(t -> t.field("category1Id").value(albumIndexQuery.getCategory1Id())));
        }
        // 如果二级分类ID不为空，则添加过滤条件
        if (!StringUtils.isEmpty(albumIndexQuery.getCategory2Id())) {
            boolQuerybuilder.filter(f -> f.term(t -> t.field("category2Id").value(albumIndexQuery.getCategory2Id())));
        }
        // 如果三级分类ID不为空，则添加过滤条件
        if (!StringUtils.isEmpty(albumIndexQuery.getCategory3Id())) {
            boolQuerybuilder.filter(f -> f.term(t -> t.field("category3Id").value(albumIndexQuery.getCategory3Id())));
        }
        // 如果属性列表不为空，则添加嵌套查询条件
        List<String> attributeList = albumIndexQuery.getAttributeList();
        if (!CollectionUtils.isEmpty(attributeList)) {
            for (String attr : attributeList) {
                String[] split = attr.split(":");
                if (null != split && split.length == 2) {
                    boolQuerybuilder.filter(f -> f.nested(n -> n.path("attributeValueIndexList")
                            .query(q -> q.bool(b -> b.must(m -> m.match(m1 -> m1.field("attributeValueIndexList.attributeId").query(split[0])))
                                    .must(m -> m.match(m1 -> m1.field("attributeValueIndexList.attributeValueId").query(split[1])))
                            ))
                    ));
                }
            }
        }
        // 如果排序条件不为空，则添加排序条件
        String order = albumIndexQuery.getOrder();
        if (!StringUtils.isEmpty(order)) {
            String[] split = order.split(":");
            if (null != split && split.length == 2) {
                String field = "";
                // 根据排序字段代码设置对应的字段名称
                switch (split[0]) {
                    case "1":
                        field = "hotScore";
                        break;
                    case "2":
                        field = "playStatNum";
                        break;
                    case "3":
                        field = "createTime";
                        break;
                }
                String finalField = field;
                // 设置排序条件
                searchRequsetBuilder.sort(s -> s.field(f -> f.field(finalField).order("asc".equals(split[1]) ? SortOrder.Asc : SortOrder.Desc)));
            }
        }
        // 计算并设置起始位置
        int from = (albumIndexQuery.getPageNo() - 1) * albumIndexQuery.getPageSize();
        searchRequsetBuilder.from(from);
        // 设置每页大小
        searchRequsetBuilder.size(albumIndexQuery.getPageSize());

        // 构建布尔查询
        BoolQuery boolQuery = boolQuerybuilder.build();
        // 设置查询条件
        searchRequsetBuilder.query(boolQuery._toQuery());

        // 构建并返回搜索请求
        SearchRequest searchRequest = searchRequsetBuilder.build();
        // 打印DSL请求内容
        System.out.println("dsl:\t" + searchRequest.toString());
        return searchRequest;
    }

    @Override
    public void lowerAlbum(Long albumId) {
        albumIndexRepository.deleteById(albumId);
    }

    @Override
    public List<String> completeSuggest(String keyword) {
        SearchResponse<SuggestIndex> searchResponse = null;
        try {
            searchResponse = elasticsearchClient.search(s -> s.index("suggestinfo")
                            .suggest(s1 -> s1.suggesters("keyword-suggest", s2 -> s2
                                            .prefix(keyword)
                                            .completion(c -> c
                                                    .field("keyword")
                                                    .skipDuplicates(true)
                                                    .fuzzy(f -> f.fuzziness("auto"))
                                                    .size(10)
                                            ))
                                    .suggesters("keywordPinyin-suggest", s2 -> s2
                                            .prefix(keyword)
                                            .completion(c -> c
                                                    .field("keywordPinyin")
                                                    .skipDuplicates(true)
                                                    .fuzzy(f -> f.fuzziness("auto"))
                                                    .size(10)
                                            ))
                                    .suggesters("keywordSequence-suggest", s2 -> s2
                                            .prefix(keyword)
                                            .completion(c -> c
                                                    .field("keywordSequence")
                                                    .skipDuplicates(true)
                                                    .fuzzy(f -> f.fuzziness("auto"))
                                                    .size(10)
                                            ))
                            )
                    , SuggestIndex.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        ArrayList<String> list = new ArrayList<>();
        list.addAll(getSuggestionTitle(searchResponse, "keyword-suggest"));
        list.addAll(getSuggestionTitle(searchResponse, "keywordPinyin-suggest"));
        list.addAll(getSuggestionTitle(searchResponse, "keywordSequence-suggest"));
//        searchResponse.suggest().get("keyword-suggest");
//        searchResponse.suggest().get("keywordPinyin-suggest");
//        searchResponse.suggest().get("keywordSequence-suggest");

        return list;
    }

    public Collection<String> getSuggestionTitle(SearchResponse<SuggestIndex> searchResponse, String suggest) {
        List<Suggestion<SuggestIndex>> suggestionList = searchResponse.suggest().get(suggest);
        if (!CollectionUtils.isEmpty(suggestionList)) {
            for (Suggestion<SuggestIndex> suggestIndexSuggestion : suggestionList) {
                List<String> list = suggestIndexSuggestion.completion().options().stream().map(option -> {
                    String title = option.source().getTitle();
                    return title;
                }).collect(Collectors.toList());
                return list;
            }
            ;
        }

        return new ArrayList<>();
    }


    @Override
/**
 * 根据一级分类ID获取频道数据
 * 该方法通过调用远程服务和 Elasticsearch 搜索来获取和处理数据
 *
 * @param category1Id 一级分类ID
 * @return 包含分类和相关数据的列表
 */
    public List<Map<String, Object>> channel(Long category1Id) {

        // 调用远程服务获取三级分类数据
        Result<List<BaseCategory3>> baseCategory3ResultList = categoryFeignClient.findTopBaseCategory3(category1Id);
        // 断言数据不为空，否则抛出异常
        Assert.notNull(baseCategory3ResultList, "远程调用三级分类数据失败");
        // 提取三级分类数据列表
        List<BaseCategory3> baseCategory3List = baseCategory3ResultList.getData();
        // 将三级分类数据转换为Map，便于后续查询
        Map<Long, BaseCategory3> category3Map = baseCategory3List.stream().collect(Collectors.toMap(BaseCategory3::getId, baseCategory3 -> baseCategory3));
        // 断言数据不为空，否则抛出异常
        Assert.notNull(baseCategory3List, "远程调用获取三类分类数据失败");
        // 提取所有三级分类ID
        List<Long> category3IdList = baseCategory3List.stream().map(BaseCategory3::getId).collect(Collectors.toList());
        // 将分类ID封装为FieldValue对象，准备用于Elasticsearch查询
        List<FieldValue> valueList = category3IdList.stream().map(category3Id -> FieldValue.of(category3Id)).collect(Collectors.toList());

        // 执行Elasticsearch搜索
        SearchResponse<AlbumInfoIndex> searchResponse = null;
        try {
            searchResponse = elasticsearchClient.search(s -> s.index("albumInfo")
                            .query(q -> q.bool(b -> b.filter(f -> f.terms(t -> t.field("category3Id").terms(t1 -> t1.value(valueList))))))
                            .aggregations("agg_category3Id", a -> a.terms(t -> t.field("category3Id")))
                            .aggregations("agg_topSix", a1 -> a1.topHits(t1 -> t1.size(6).sort(st -> st.field(f -> f.field("hotScore").order(SortOrder.Desc)))))

                    , AlbumInfoIndex.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 获取聚合结果
        Aggregate aggregate = searchResponse.aggregations().get("agg_category3Id");

        // 处理聚合结果，生成最终的列表数据
        List<Map<String, Object>> listMap = aggregate.lterms().buckets().array().stream().map(bucket -> {
            Map<String, Object> map = new HashMap<>();
            long category3Id = bucket.key();
            Aggregate aggTopSix = bucket.aggregations().get("agg_topSix");
            List<AlbumInfoIndex> albumInfoIndexList = aggTopSix.topHits().hits().hits().stream().map(hit -> {
                String data = hit.source().toString();
                AlbumInfoIndex albumInfoIndex = JSONObject.parseObject(data, AlbumInfoIndex.class);
                return albumInfoIndex;
            }).collect(Collectors.toList());
            map.put("baseCategory3", category3Map.get(category3Id));
            map.put("list", albumInfoIndexList);
            return map;
        }).collect(Collectors.toList());

        // 返回处理后的数据列表
        return listMap;
    }

    @Override
    public void upateLatelyAlbumRanking() {
        Result<List<BaseCategory1>> baseCategory1Result = categoryFeignClient.findAllCategory1();
        Assert.notNull(baseCategory1Result,"远程调用获取一级分类失败");
        List<BaseCategory1> baseCategory1List = baseCategory1Result.getData();
        Assert.notNull(baseCategory1List,"远程调用获取一级分类失败");

        for (BaseCategory1 baseCategory1 : baseCategory1List) {
            String[] rankingDimensionArray = {
                    "hotScore", "playStatNum", "subscribeStatNum", "buyStatNum", "commentStatNum"
            };

            for (String rankingDimension : rankingDimensionArray) {
                SearchResponse<AlbumInfoIndex> searchResponse = null;
                try {
                    searchResponse = elasticsearchClient.search(s -> s.index("albuminfo")
                                    .query(q -> q.term(t -> t.field("category1Id").value(baseCategory1.getId())))
                                    .sort(st -> st.field(f -> f.field(rankingDimension).order(SortOrder.Desc)))
                            , AlbumInfoIndex.class);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

                List<AlbumInfoIndex> albumInfoIndexList = searchResponse.hits().hits().stream().map(Hit::source).collect(Collectors.toList());
                redisTemplate.opsForHash().put(RedisConstant.RANKING_KEY_PREFIX+baseCategory1.getId(),rankingDimension,albumInfoIndexList);


            }

        }

    }

    @Override
    public void upperAlbum(Long albumId) {
        // 创建一个AlbumInfoIndex对象，用于存储专辑信息索引
        AlbumInfoIndex albumInfoIndex = new AlbumInfoIndex();

        // 调用远程服务获取专辑信息
        CompletableFuture<AlbumInfo> albumInfoCompletableFuture = CompletableFuture.supplyAsync(() -> {
            Result<AlbumInfo> infoResult = albumInfoFeignClient.getAlbumInfo(albumId);

            // 确保远程调用结果不为空
            Assert.notNull(infoResult, "远程调用失败");

            // 从调用结果中获取专辑信息实体
            AlbumInfo albumInfo = infoResult.getData();
            // 确保专辑信息实体不为空
            Assert.notNull(albumInfo, "远程调用albumInfo失败");

            // 将专辑信息实体的属性复制到专辑信息索引对象中
            BeanUtils.copyProperties(albumInfo, albumInfoIndex);

            // 获取专辑属性值列表
            List<AlbumAttributeValue> albumAttributeValueVoList = albumInfo.getAlbumAttributeValueVoList();

            // 将专辑属性值列表转换为属性值索引列表
            List<AttributeValueIndex> attributeValueIndexList = albumAttributeValueVoList.stream().map(albumAttributeValue -> {
                AttributeValueIndex attributeValueIndex = new AttributeValueIndex();
                attributeValueIndex.setAttributeId(albumAttributeValue.getAttributeId());
                attributeValueIndex.setValueId(albumAttributeValue.getValueId());
                return attributeValueIndex;
            }).collect(Collectors.toList());

            // 将属性值索引列表设置到专辑信息索引对象中
            albumInfoIndex.setAttributeValueIndexList(attributeValueIndexList);

            return albumInfo;
        }, threadPoolExecutor).exceptionally(ex -> {
            System.out.println(ex.getMessage());
            return new AlbumInfo();
        });

        CompletableFuture<Void> categoryCompletableFuture = albumInfoCompletableFuture.thenAcceptAsync(albumInfo -> {
            // 调用Feign客户端获取基础分类视图
            Result<BaseCategoryView> categoryViewResult = categoryFeignClient.getCategoryView(albumInfo.getCategory3Id());
            // 断言分类视图结果不为空，确保远程调用成功
            Assert.notNull(categoryViewResult, "远程调用获取分类视图失败");
            // 从分类视图结果中获取基础分类视图对象
            BaseCategoryView baseCategoryView = categoryViewResult.getData();
            // 设置相册信息索引对象的分类ID
            albumInfoIndex.setCategory1Id(baseCategoryView.getCategory1Id());
            albumInfoIndex.setCategory2Id(baseCategoryView.getCategory2Id());
        }, threadPoolExecutor).exceptionally(ex -> {
            System.out.println(ex.getMessage());
            return null;
        });
        CompletableFuture<Void> userCompletableFuture = albumInfoCompletableFuture.thenAcceptAsync(albumInfo -> {
            // 调用远程服务获取用户信息
            Result<UserInfoVo> userInfoResult = userInfoFeignClient.getUserInfo(albumInfo.getUserId());
            // 确保远程服务调用返回结果不为空
            Assert.notNull(userInfoResult, "远程调用用户信息失败");
            // 从返回结果中提取用户信息
            UserInfoVo userInfoVo = userInfoResult.getData();

            Assert.notNull(userInfoVo, "远程调用获取");
            // 设置专辑信息中的发布者名称为获取到的用户昵称
            albumInfoIndex.setAnnouncerName(userInfoVo.getNickname());
        }, threadPoolExecutor).exceptionally(ex -> {
            System.out.println(ex.getMessage());
            return null;
        });


        // 设置专辑的播放统计数量，用于反映专辑的受欢迎程度
        albumInfoIndex.setPlayStatNum(new Random().nextInt(100000));
        // 设置专辑的购买统计数量，用于反映专辑的商业价值
        albumInfoIndex.setBuyStatNum(new Random().nextInt(100000));
        // 设置专辑的评论统计数量，用于反映专辑的用户互动程度
        albumInfoIndex.setCommentStatNum(new Random().nextInt(100000));
        // 设置专辑的订阅统计数量，用于反映用户对专辑的兴趣程度
        albumInfoIndex.setSubscribeStatNum(new Random().nextInt(100000));
        // 设置专辑的热度得分，用于综合反映专辑的热门程度
        albumInfoIndex.setHotScore((double) new Random().nextInt(100000));

        try {
            System.out.println("categoryCompletableFuture.get() = " + categoryCompletableFuture.get());
            System.out.println("userCompletableFuture.get() = " + userCompletableFuture.get());
            if (ObjectUtils.isEmpty(albumInfoCompletableFuture.get())) {
                log.info("远程调用失败");
                return;
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }


        CompletableFuture.allOf(
                albumInfoCompletableFuture,
                categoryCompletableFuture,
                userCompletableFuture
        ).join();

        // 记录日志，准备将专辑信息索引数据插入到Elasticsearch中
        log.info("将数据插入到es中");
        // 保存专辑信息索引到Elasticsearch中，以便于快速检索和查询
        albumIndexRepository.save(albumInfoIndex);

        SuggestIndex suggestIndex = new SuggestIndex();
        suggestIndex.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        suggestIndex.setTitle(albumInfoIndex.getAlbumTitle());
        suggestIndex.setKeyword(new Completion(new String[]{albumInfoIndex.getAlbumTitle()}));
        suggestIndex.setKeyword(new Completion(new String[]{PinYinUtils.toHanyuPinyin(albumInfoIndex.getAlbumTitle())}));
        suggestIndex.setKeywordSequence(new Completion(new String[]{PinYinUtils.getFirstLetter(albumInfoIndex.getAlbumTitle())}));
        suggestIndexRepository.save(suggestIndex);

        SuggestIndex suggestIndexIntro = new SuggestIndex();
        suggestIndexIntro.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        suggestIndexIntro.setTitle(albumInfoIndex.getAlbumIntro());
        suggestIndexIntro.setKeyword(new Completion(new String[]{albumInfoIndex.getAlbumIntro()}));
        suggestIndexIntro.setKeyword(new Completion(new String[]{PinYinUtils.toHanyuPinyin(albumInfoIndex.getAlbumIntro())}));
        suggestIndexIntro.setKeywordSequence(new Completion(new String[]{PinYinUtils.getFirstLetter(albumInfoIndex.getAlbumIntro())}));
        suggestIndexRepository.save(suggestIndexIntro);

    }
}
